using Microsoft.AspNetCore.Mvc;
using Common.Helper;
using test.Models;

namespace test.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PageController : ControllerBase
    {
        private readonly hongjiContext _db;
        public PageController(hongjiContext db)
        {
            _db = db;
        }

        [HttpGet(Name = "PageID")]
        public Page Get(int ID = 1)
        {
            Page P = new();
            var p = _db.Pages.FirstOrDefault(x => x.Id == ID);
            if (p != null)
            {
                P = p;
            }
            return P;
        }

        [HttpDelete(Name = "DeletePageList")]
        public bool Del(int ID = 0)
        {
            var p = _db.Pages.FirstOrDefault(x => x.Id == ID);
            if (p != null)
            {
                _db.Pages.Remove(p);
            }
            LogHelper.Write("Invoke Delete");
            if (_db.SaveChanges() > 0)
            {
                return true;
            }
            return false;
        }

        [HttpPost(Name = "InsertPageList")]
        public bool Post(Page P)
        {
            var p = _db.Pages.FirstOrDefault(x => x.Id == P.Id);
            if (p == null)
            {
                Page p1 = new()
                {
                    Title = P.Title,
                    Content = P.Content
                };
                _db.Pages.Add(p1);
            }
            else
            {
                p.Title = P.Title;
                p.Content = P.Content;
                _db.Pages.Attach(p);
            }

            LogHelper.Write("Invoke Post");
            if (_db.SaveChanges() > 0)
            {
                return true;
            }
            return false;
        }

    }
}